package com.terry.activity.util;

import com.terry.activity.bean.constant.WeChatConstant;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * Create On 18/4/19.
 *
 * @author TerrySolar
 */
@Component
public class WeChatUtil {

    /**
     * 校验微信签名
     * @param request HttpServletRequest
     * @return 返回签名是否通过
     */
    public boolean checkSign(HttpServletRequest request) {

        // 获取所有参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        if (signature == null || timestamp == null || nonce == null) {
            return false;
        }

        // 字典序排列
        String[] arr = new String[] {WeChatConstant.APP_TOKEN,timestamp,nonce};
        Arrays.sort(arr);

        StringBuffer data = new StringBuffer();
        for (String str:arr) {
            data.append(str);
        }


        // SHA-1加密
        String shaStr = DigestUtils.sha1Hex(data.toString());

        return Objects.equals(shaStr, signature);

    }


    /**
     * 构造获取网页授权AccessToken地址
     * @param code 微信Code
     * @return URL
     */
    public String constructAccessTokenUrl(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConstant.APP_ID +
                "&secret=" + WeChatConstant.APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        return url;
    }


    /**
     * 检查是否微信授权状态
     *
     * @param request HttpServletRequest
     * @return boolean
     */
    public boolean checkAuth(HttpServletRequest request) {
        return !(request.getSession().getAttribute("openid") == null);
    }
}

